import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

class Station{
    private int numberOfTickets=100;

    private Lock lock=new ReentrantLock();


    public int getNumberOfTickets() {
        return numberOfTickets;
    }

    public void setNumberOfTickets(int numberOfTickets) {
        this.numberOfTickets = numberOfTickets;
    }
        /*此时没上锁三人同时使用导致不同的线程来回穿插访问numberOfTickets参数
         前一个线程已经卖了这张票但是后一个程序不知道又重复卖了一遍甚至多遍左后卖的票数比总票数都多
        */
    public void sell(){
        Thread thread = Thread.currentThread();
        if (this.getNumberOfTickets()>0){
            System.out.println(thread.getName()+"卖了第"+(100-this.getNumberOfTickets()+1)+"张票");
            this.setNumberOfTickets(this.getNumberOfTickets()-1);
            System.out.println("还剩"+this.getNumberOfTickets()+"张票");
        }else {
            System.out.println("来晚了没票了");
            System.exit(0);
        }
    }

            //同步代码块
//        public void sell(){
//        synchronized (this){
//            if (this.getNumberOfTickets()>0){
//                System.out.println("卖了第"+(100-this.getNumberOfTickets()+1)+"张票");
//                this.setNumberOfTickets(this.getNumberOfTickets()-1);
//                System.out.println("还剩"+this.getNumberOfTickets()+"张票");
//            }else {
//                System.out.println("来晚了没票了");
//                System.exit(0);
//            }
//        }
//
//    }


        //同步方法
//    public synchronized void sell(){
//        if (this.getNumberOfTickets()>0){
//            System.out.println("卖了第"+(100-this.getNumberOfTickets()+1)+"张票");
//            this.setNumberOfTickets(this.getNumberOfTickets()-1);
//            System.out.println("还剩"+this.getNumberOfTickets()+"张票");
//        }else {
//            System.out.println("来晚了没票了");
//            System.exit(0);
//        }
//
//    }



        //Lock锁
//    public void sell(){
//        lock.lock();
//        if (this.getNumberOfTickets()>0){
//            System.out.println("卖了第"+(100-this.getNumberOfTickets()+1)+"张票");
//            this.setNumberOfTickets(this.getNumberOfTickets()-1);
//            System.out.println("还剩"+this.getNumberOfTickets()+"张票");
//        }else {
//            System.out.println("来晚了没票了");
//            System.exit(0);
//        }
//        lock.unlock();
//    }


}

public class NumberTwo {
    public static void main(String[] args) {
        Station station=new Station();
        Thread thread=new Thread(new Runnable() {
            @Override
            public void run() {
                station.sell();
            }
        });
        new Thread(()->{
            while (true){
                station.sell();
            }
        }).start();
        new Thread(()->{
            while (true){
                station.sell();
            }
        }).start();
    }
}
